/*===========================================================
 
 .---=||||[ B L O O D Y ]|||||=====================----------....
 |                                                              |
 |    THE  M O S T   B L O O D Y  GAME EVER!                    |
 |                                                              |
 |    bloody harvest is coming... soon,                         |
 |                                              heil Satan!     |
 !                                                              !
 .                                                              ,
  ~~~~-------------================================|||||||||==-~




 Name-Space: {core, logic, editor}
 Module: {draw, coll, scgr, ...}
 Class: <name of class>
 Last modification:  <author>, <time>

 TODO:
 <-------- todo #1 ---------->
 <-------- todo #2 ---------->
 <-------- todo #3 ---------->
        ............
 <-------- todo #n ---------->

 FIX:
 <-------- fix #1 ----------->
 <-------- fix #1 ----------->
         ..........
 <-------- fix #n ----------->




 
 
 ============================================================*/
#include "core/draw/Material.h"
#include "core/draw/TextureManager.h"
namespace core
{
	namespace draw
	{

		Material::Material()
		{
			shininess = 0;
			ambient = Vector4f(0.2, 0.2, 0.2, 1);
			diffuse = Vector4f(0.8, 0.8, 0.8, 1);
			specular = Vector4f(0, 0, 0, 1);
			emissive = Vector4f(0, 0, 0, 1);
			texture = 0;
			materialType = Material::Nothing;
		}

		Material::~Material()
		{
		}

		void Material::bind()
		{
			if (materialType & Material::Ambient)
				glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, (const float*)&ambient);
			if (materialType & Material::Diffuse)
				glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, (const float*)&diffuse);
			if (materialType & Material::Specular)
				glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, (const float*)&specular);
			if (materialType & Material::Emissive)
				glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, (const float*)&emissive);
			if (materialType & Material::Shininess)
				glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shininess);
			if (texture) texture->bind();
		}

		Material* Material::fromConfig(const Config& cfg)
		{
			Material* ret = new Material();
			if (cfg.hasKey("ambient"))
			{
				cfg["ambient"].to(ret->ambient);
			}
			if (cfg.hasKey("specular"))
			{
				cfg["specular"].to(ret->specular);
			}
			if (cfg.hasKey("diffuse"))
			{
				cfg["diffuse"].to(ret->diffuse);
			}
			if (cfg.hasKey("shininess"))
			{
				cfg["shininess"].to(ret->shininess);
			}
			if (cfg.hasKey("texture"))
			{
				String texName;
				cfg["texture"].to(texName);
				TextureManager& mgr = TextureManager::instance();
				ret->texture = mgr.get(texName);
			}
			return ret;
		}
	}
}

